package leetcode.每日一题;

import org.junit.Test;

import java.util.*;

/**
 * @author ：zsy
 * @date ：Created 2021/11/23 21:00
 * @description：https://leetcode-cn.com/problems/buddy-strings/
 */
public class 亲密字符串 {
    @Test
    public void test() {
        Solution solution = new Solution();
        System.out.println(solution.buddyStrings("aa","aa"));
    }


    class Solution {
        public boolean buddyStrings(String s, String goal) {
            if (s.length() != goal.length()) return false;

            if (s.equals(goal)) {
                int[] counts = new int[26];
                for (int i = 0; i < s.length(); i++) {
                    int count = ++counts[s.charAt(i) - 'a'];
                    if (count > 1) return true;
                }
                return false;
            } else {
                int first = -1, second = -1;
                for (int i = 0; i < s.length(); i++) {
                    if (s.charAt(i) != goal.charAt(i)) {
                        if (first == -1) {
                            first = i;
                        } else if (second == -1) {
                            second = i;
                        } else
                            return false;
                    }
                }
                return (second != -1
                        && s.charAt(first) == goal.charAt(second)
                        && s.charAt(second) == goal.charAt(first));
            }
        }
    }
}
